﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Microsoft.IdentityModel.Tokens;
using WebApplicationFileSys.Models;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class JwtAuthorization : AuthorizeAttribute
{
    private readonly string secretKey;

    public JwtAuthorization(string secretKey)
    {
        this.secretKey = secretKey;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        try
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            // 从请求头中获取JWT
            var authorizationHeader = httpContext.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
            {
                var token = authorizationHeader.Substring("Bearer ".Length);


                SecurityToken validatedToken;
                try
                {
                    // 验证JWT的有效性
                    tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
                }
                catch (Exception)
                {

                    return false;
                }

                var jwt = tokenHandler.ReadJwtToken(token);
                var tokenName = jwt.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Name && claim.Value.Equals(LoginMode.username));
                if (tokenName != null && validatedToken.ValidTo >= DateTime.UtcNow)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

    private TokenValidationParameters GetValidationParameters()
    {
        return new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,

            ValidIssuer = KeyValueConfig.issuer,
            ValidAudience = KeyValueConfig.audience,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
        };
    }
}
